package com.yunqi.autovender.adapter;

import android.databinding.DataBindingUtil;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import com.yunqi.autovender.R;
import com.yunqi.autovender.databinding.ProductItemBinding;

import java.util.ArrayList;
import java.util.List;

import google.architecture.coremodel.callback.ProductItemClickCallback;
import google.architecture.coremodel.datamodel.http.entities.ProductData;

/**
 * 竖屏的ProductAdapter
 */
public class VProductAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>  {
    List<ProductData.Product> productList=new ArrayList<>();
    ProductItemClickCallback productItemClickCallback;


    @NonNull
    @Override
    public RecyclerView.ViewHolder  onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ProductItemBinding binding = DataBindingUtil
                .inflate(LayoutInflater.from(parent.getContext()), R.layout.product_item,
                        parent, false);
        binding.setCallback(productItemClickCallback);
        return new ProductViewHolder(binding);
    }

    public VProductAdapter(@Nullable ProductItemClickCallback itemClickCallback, List<ProductData.Product> productList) {
        productItemClickCallback = itemClickCallback;
        this.productList=productList;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder  holder, int position) {
        if(holder instanceof VProductAdapter.ProductViewHolder) {
            VProductAdapter.ProductViewHolder vHolder=(VProductAdapter.ProductViewHolder)holder;
            vHolder.binding.setProductItem(productList.get(position));
            vHolder.binding.executePendingBindings();
        }
    }
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder  holder, int position, @NonNull List<Object> payloads) {
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position);
        } else {
            if(holder instanceof VProductAdapter.ProductViewHolder) {
                VProductAdapter.ProductViewHolder vHolder=(VProductAdapter.ProductViewHolder)holder;
                String payload = (String) payloads.get(0);
                if (TextUtils.equals(payload, "updateStack")) {
                    vHolder.binding.setProductItem(productList.get(position-1));
                    vHolder.binding.executePendingBindings();
                }
            }

        }
    }

    @Override
    public int getItemCount() {
         return productList == null ? 0 : productList.size();
    }


    static class ProductViewHolder extends RecyclerView.ViewHolder {
        ProductItemBinding binding;
        public ProductViewHolder(ProductItemBinding binding ) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }

}
